package server;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;

import util.MyParser;

/**
 * @author ic08jh7
 * 
 */
public final class ServerSend {

	public static void sendToPlayer(ArrayList<Participant> pl, String name,
			String message) {
		Participant p = null;
		for (int i = 0; i < pl.size(); i++) {
			if (pl.get(i).getName().equals(name)) {
				p = pl.get(i);
			}
		}
		if (p != null) {
			try {
				OutputStream out = p.getSocket().getOutputStream();
				out.write((message + "\n").getBytes());
				out.flush();
			} catch (IOException e) {
				System.out.println("Unable to send " + message + " to " + name);
			}
		}
	}

	public static void sendToPlayer(ArrayList<Participant> pl, int player,
			String s) {
		try {
			OutputStream out = pl.get(player).getSocket().getOutputStream();
			out.write((s + "\n").getBytes());
			out.flush();
		} catch (IOException e) {
			System.out.println("Unable to send " + s + " to player with ID "
					+ player);
		}
	}

	public static void sendToAll(ArrayList<Participant> pl, String s) {
		for (int i = 0; i < pl.size(); i++) {
			sendToPlayer(pl, i, s);
		}
	}

	public static void serverChatSendToAll(ArrayList<Participant> pl, String s) {
		String message = MyParser.codeToChat(s, "Server");
		for (int i = 0; i < pl.size(); i++) {
			sendToPlayer(pl, i, message);
		}
	}

	public static void serverGameSendToAll(ArrayList<Participant> pl, String s) {

		String message = MyParser.codeToGame(s);
		for (int i = 0; i < pl.size(); i++) {
			sendToPlayer(pl, i, message);
		}
	}
}
